package com.liy.framework.web.spring.aop;

import com.liy.framework.common.extvo.LogAttributeInfo;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import com.liy.framework.web.spring.utils.WebTools;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


public class SystemOperationLogAspect {
    protected static Logger log = LoggerFactory.getLogger(SystemOperationLogAspect.class);
    private long startTime = 0L;

    public SystemOperationLogAspect() {}

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    private void anyMethod() {}


    @AfterThrowing( pointcut = "anyMethod()", throwing = "e")
    public void doAfterThrow(JoinPoint joinPoint, Throwable e) {
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        long time = System.currentTimeMillis() - this.startTime;
        String tip = time > 1000L ? "超过设定值1000ms" : "";
        log.info(String.format("服务：%s,处理耗时[%dms],%s,处理异常：%s", request.getRequestURL(), time, tip, e.getMessage()), e, new LogAttributeInfo(request.getRequestURL().toString(), time));
    }


    @Around("anyMethod()")
    public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
        this.startTime = System.currentTimeMillis();
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        Object object = pjp.proceed();
        long time = System.currentTimeMillis() - this.startTime;
        String tip = time > 1000L ? "超过设定值1000ms" : "";
        log.info(String.format("服务：%s,处理耗时[%dms],%s,响应数据：%s", request.getRequestURL(), time, tip, object != null ? object.toString() : "null"), new LogAttributeInfo(request.getRequestURL().toString(), time));
        Map<?, ?> params2 = com.liy.framework.web.spring.utils.WebTools.getRequestParams(request);
        log.info("请求参数：" + params2.toString());
        if (log.isDebugEnabled()) {
            Map<?, ?> params = WebTools.getRequestParams(request);
            log.info("请求参数：" + params.toString());
        }
        return object;
    }
}
